﻿using libemscontrol.act;
using System;
using System.Collections.Generic;
using System.Threading;

namespace libcontrol
{

    public enum ActionCmd
    {
        AC_DATA_SYNC = 2,
    };

    public class InterfaceMsg
    {
       public  byte ID;
       public  string Name;
    }
    public class CEmsAct
    {
        private static CEmsAct pEmsActInstacne = null;        
        public Dictionary<ActionCmd, CSingleAct> m_ActList;
        public KrBoard McuCard = null;
        public bool m_IsBoardInit = false;
        public bool IsTestMode = false;
        private bool IsConnect = false;
        public List<InterfaceMsg> ltInterface = new List<InterfaceMsg>();
        public List<InterfaceMsg> ltMsg = new List<InterfaceMsg>();
        CEmsAct()
        {
            McuCard = new KrBoard();
            m_ActList = new Dictionary<ActionCmd, CSingleAct>();
            m_ActList.Add(ActionCmd.AC_DATA_SYNC, new DataSync());
        }

        public int DoAction(int boardid,int ActionNum)
        {
            if(!IsConnect)
            {
                return 0;
            }
            Logger.WriteRunLog("DoAction:"+boardid.ToString()+"\t"+ActionNum.ToString());
            switch(boardid)
            {
                case 1:
                    m_ActList[(ActionCmd)ActionNum].StartOp();
                    break;
                case 2:
                    McuCard.DoAction((byte)ActionNum);
                    break;
            }
            return 0;
        }

        public bool ShareMem(byte[] SendData, int SendLen,ref byte[] RecvData, int RecvLen)
        {
           return McuCard.ShareMem(SendData, SendLen, ref RecvData, RecvLen);
        }

        public bool SharePC(byte[] SendData, int SendLen, ref byte[] RecvData, int RecvLen)
        {
            return McuCard.SharePC(SendData, SendLen, ref RecvData, RecvLen);
        }

        private static readonly object locker = new object();
        public static CEmsAct GetInstance()
        {
            lock(locker)
            {
                if (pEmsActInstacne == null)
                {
                    pEmsActInstacne = new CEmsAct();
                    return pEmsActInstacne;
                }
            }
            return pEmsActInstacne;
        }

        private void GetInterfaceMsg()
        {
            try
            {
                var count = McuCard.WalkInterfaceMsgCount();
                byte index = 0;
                Logger.WriteRunLog("总的接口数量:" + count.InterfaceCount);
                while (index < count.InterfaceCount)
                {
                    var ltTemp = McuCard.GetInterfaceInfo(index);
                    foreach (var item in ltTemp)
                    {
                        ltInterface.Add(item);
                    }
                    index += 6;
                }

                index = 0;
                while (index < count.MsgCount)
                {
                    var ltTemp = McuCard.GetMsgInfo(index);
                    foreach (var item in ltTemp)
                    {
                        ltMsg.Add(item);
                    }
                    index += 6;
                }
            }
            catch(Exception ex)
            {
                Logger.WriteRunLog(ex.ToString()) ;
            }           
        }

        public bool Init(string nPort)
        {
            Logger.WriteRunLog("控制卡端口:"+ nPort);         
            if(McuCard.Connect("Uart", nPort)>0)
            {
                IsConnect = true;
                GetInterfaceMsg();
                MachineDoAction(ActionCmd.AC_DATA_SYNC);
                Logger.WriteRunLog("=====================设备开始运行===============================");
                new Thread(new ThreadStart(Running)).Start();
                return true;
            }
            else
            {
                RecvMemData.GetInstance().SendCommErrorMsg();
                return false;
            }         
        }

        public void MachineDoAction(ActionCmd actionCmd)
        {
            if (m_ActList.ContainsKey(actionCmd))
            {
                m_ActList[actionCmd].StartOp();
            }
        }

        public bool IsWorking(ActionCmd actionCmd)
        {
            if (m_ActList.ContainsKey(actionCmd))
            {
                return m_ActList[actionCmd].m_bEn;
            }
            return false;
        }

        public int QueryActionResult(ActionCmd actionCmd)
        {
            if (m_ActList.ContainsKey(actionCmd))
            {
                return m_ActList[actionCmd].m_nResult; 
            }
            return 0;
        }

        public void StopAction(ActionCmd actionCmd)
        {
            if (m_ActList.ContainsKey(actionCmd))
            {
                m_ActList[actionCmd].Stop();
            }
        }

        void EventProcess(CSingleAct act)
        {
            for (int i = 0; i < act.EventCount; i++)
            {
                switch (act.EventQueue[i].ThisEventType)
                {
                    case EventType.TYPE_TIME:
                        if (act.CheckOpTimeDelay())
                        {
                            act.EventCount = 0;
                            act.m_nStep = act.EventQueue[i].SameStep;
                            act.Working();
                            return;
                        }
                        break;

                    case EventType.TYPE_ACTION:
                        var result = m_ActList[(ActionCmd)act.EventQueue[i].EventId].m_nResult;

                        if (result == 0xff)
                        {
                            act.EventCount = 0;
                            act.m_nStep= act.EventQueue[i].SameStep;
                            act.Working();
                        }
                        else if (result > 0)
                        {
                            act.EventCount = 0;
                            act.m_nStep = act.EventQueue[i].DiffStep;
                            act.Working();
                        }
                        break;               
                }
            }
        }

        public void Close()
        {
            IsConnect = false;
            McuCard.CloseCom();
        }

        private void Running()
        {          
            while (IsConnect)
            {       
               
                foreach(var actitem in m_ActList.Values)
                {
                    if (actitem.m_bEn)
                    {
                        if(actitem.EventCount>0)
                        {
                            EventProcess(actitem);
                        }
                        else
                        {
                            actitem.Working();
                        }
                        
                        actitem.DealResult();
                    }
                }

                Thread.Sleep(2);
            }
           
        }
    }
}
